package com.currency.mall.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.currency.mall.Constant;
import com.currency.mall.event.LoginEvent;
import com.currency.mall.event.MainEvent;
import com.currency.mall.util.MD5Util;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.currency.mall.R;
import com.currency.mall.entity.LoginBean;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.main.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/11.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.input_user)
    EditText inputUser;
    @BindView(R.id.rl_user)
    RelativeLayout rlUser;
    @BindView(R.id.input_pwd)
    EditText inputPwd;
    @BindView(R.id.rl_pwd)
    RelativeLayout rlPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.password_img)
    ImageView passwordImg;
    private boolean mDisplayFlg = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        EventBus.getDefault().register(this);
        PreferenceUtils.clearLoginInfo();
        init();
    }

    private void init() {
        btnLogin.setClickable(false);
        btnLogin.getBackground().setAlpha(50);
        inputUser.addTextChangedListener(phoneTextWatcher);
        inputPwd.addTextChangedListener(pwdTextWatcher);
    }


    TextWatcher phoneTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = inputUser.getText().toString().trim();
            String pwd = inputPwd.getText().toString().trim();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(s)) {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(50);
                btnLogin.setClickable(false);
            } else {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(250);
                btnLogin.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                rlUser.setVisibility(View.INVISIBLE);
            } else {
                rlUser.setVisibility(View.VISIBLE);
            }
        }
    };


    TextWatcher pwdTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = inputUser.getText().toString().trim();
            String pwd = inputPwd.getText().toString().trim();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(s)) {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(50);
                btnLogin.setClickable(false);
            } else {
                btnLogin.setBackgroundResource(R.drawable.btn_bg);
                btnLogin.getBackground().setAlpha(250);
                btnLogin.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                rlPwd.setVisibility(View.INVISIBLE);
            } else {
                rlPwd.setVisibility(View.VISIBLE);
            }
        }
    };

    @OnClick({R.id.ll_back,R.id.rl_user, R.id.rl_pwd, R.id.btn_login, R.id.tv_register, R.id.password_img, R.id.tv_fast_register, R.id.tv_forgot_pwd})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.rl_user:
                inputUser.setText("");
                rlUser.setVisibility(View.GONE);
                break;
            case R.id.rl_pwd:
                inputPwd.setText("");
                rlPwd.setVisibility(View.GONE);
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_register:
                intent = new Intent(getContext(), RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.password_img:
                passwordTransformation();
                break;
            case R.id.tv_fast_register:
                intent = new Intent(getContext(), SpeedLoginActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forgot_pwd:
                intent = new Intent(getContext(), ForgetPwdActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void passwordTransformation() {

        if (!mDisplayFlg) {
            // display password text, for example "123456"
            inputPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            inputPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        mDisplayFlg = !mDisplayFlg;

        inputPwd.postInvalidate();

        if (mDisplayFlg) {
            passwordImg.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            passwordImg.setImageResource(R.drawable.yanjing_guanbi);
        }
        inputPwd.setSelection(inputPwd.getText().toString().length());
    }

    public void login() {
        String pwd = inputPwd.getText().toString().trim();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userName",inputUser.getText().toString().trim() );
        hashMap.put("passwd", MD5Util.toMD5(pwd).toLowerCase());
//        hashMap.put("passwd",pwd);
        NetWork.getLoginApi().login(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        if (loginBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("登录成功", 200);
                            PreferenceUtils.saveToken(loginBean.getToken());
                            EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                            finish();
                        } else {
                            ToastUitl.show(loginBean.getMsg(), 200);
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        switch (event.action) {
            case LoginEvent.LOGIN_STATUS:
                startActivity(new Intent(getContext(),MainActivity.class));
                EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
